package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleServices;
import com.example.forum.services.IBoardServices;
import com.example.forum.services.IUserServices;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.istack.internal.NotNull;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * date: 2024/09/11 19:55<br/>
 * Description:
 * 文章接口
 *
 * @author: jmy <br/>
 */

@Api(tags = "文章接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private IArticleServices articleServices;
    @Resource
    private IBoardServices boardServices;
    @Resource
    private IUserServices userServices;

    /**
     * date: 2024/09/11 19:44<br/>
     * Description: 新增文章
     *
     * @param
     * @author: jmy <br/>
     */
    @ApiOperation("新增文章")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request, @RequestParam("title") @ApiParam("文章标题") @NotNull String title
            , @RequestParam("content") @ApiParam("文章内容") @NotNull String content
            , @RequestParam("boardId") @ApiParam("板块号") @NotNull Long boardId) {

        log.info("board/ 接收参数 title:" + title + " content:" + content + " boardId:" + boardId);

        //判断用户是否处于禁言状态
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        System.out.println(user);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED.getMessagesg());
        }

        //判断板块是否异常
        Board board = boardServices.selectByPrimaryKey(boardId);
        if (board == null) {
            log.error(ResultCode.FAILED_BOARD_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }

        //将用户传过来的信息封装成article
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setBoardId(boardId);
        article.setUserId(user.getId());

        //新增帖子
        if (articleServices.create(article) == 0) {
            return AppResult.failed(ResultCode.FAILED_CREATE.toString());
        }
        return AppResult.success("新增帖子成功");
    }

    /**
     * date: 2024/09/14 10:07<br/>
     * Description: 点击板块，出现该板块下相应的文章，展示少量用户信息,在t_article中根据板块号查询文章
     * @param boardId 板块号 可以为空
     * @param key 搜索框中的关键字
     * @author: jmy <br/>
     */
    @ApiOperation("获取相应板块的帖子")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam("板块id") @RequestParam(value = "boardId", required = false) Long boardId,
                                                    @ApiParam("搜索框中的关键字") @RequestParam(value = "key",required = false) String key) throws JsonProcessingException {
        //定义返回列表
        List<Article> articles;

        ObjectMapper objectMapper = null;


        //判断是否根据关键字查询
        if (key != null){
            //在标题中匹配
            List<Article> articlesByTitle = articleServices.selectAllByTitle(key);
            //在内容中匹配
            List<Article> articlesByContent = articleServices.selectAllByContent(key);
            //拼接
            if (articlesByTitle != null){
                if (articlesByContent != null){
                    for (Article article : articlesByContent){
                        //判断是否引进被加入帖子列表
                        if (!articlesByTitle.contains(article)){
                            articlesByTitle.add(article);
                        }
                    }
                    return AppResult.success(articlesByTitle);
                }
                return AppResult.success(articlesByTitle);
            }else if (articlesByContent!=null){
                return AppResult.success(articlesByContent);
            }
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        //boardId不为空 根据boardId 查询
        if (boardId != null ) {
            //参数合法性校验
            if (boardId <= 0) {
                return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            } else {
                articles = articleServices.selectAllByBoardId(boardId);
            }
        } else {//boardId为空 全列查询
            articles = articleServices.selectAll();
        }
        //如果集合为空，那么就创建一个空集合
        if (articles == null) {
            articles = new ArrayList<>();
        }
        return AppResult.success(articles);
    }

    /**
     * date: 2024/09/14 18:38<br/>
     * Description: 点击帖子详情，根据帖子id查询
     *
     * @param id 帖子id
     * @author: jmy <br/>
     */
    @ApiOperation("请求帖子详情")
    @GetMapping("/details")
    public AppResult<Article> selectDetailById(HttpServletRequest request, @ApiParam("帖子id") @NotNull @RequestParam("id") Long id) {
        log.info("article/details  接收参数: articleId:" + id);
        if (id <= 0) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        Article article = articleServices.selectDetailById(id);
        if (article == null) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
        }
        //获取登录用户信息
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);

        //设置isOwn 标志
        article.setOwn(Article.judge(user.getId(), article.getUserId()));
        System.out.println(Article.judge(user.getId(), article.getUserId()));
        return AppResult.success(article);
    }

    /**
     * date: 2024/09/15 12:59<br/>
     * Description: 修改帖子内容
     *
     * @author: jmy <br/>
     */
    @PostMapping("/modify")
    @ApiOperation("更新帖子信息")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("帖子id") @NotNull @RequestParam("id") Long id,
                            @ApiParam("帖子标题") @NotNull @RequestParam("title") String title,
                            @ApiParam("帖子内容") @NotNull @RequestParam("content") String content) {
        log.info("article/modify  接收参数: id: " + id + "title: " + title + "content: " + content);

        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);

        //判断用户是否被禁言
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //登录用户id
        Long userId = user.getId();
        //查询帖子作者信息
        Article article = articleServices.selectById(id);

        if (article != null) {
            Long authorId = article.getUserId();
            //判断 帖子作者与 登录用户 是否相同
            if (Article.judge(userId, authorId)) {
                //判断帖子状态
                if (article.getState() == 0 && article.getDeleteState() == 0) {
                    //更新帖子
                    boolean result = articleServices.modify(id, title, content);
                    if (result) {
                        log.info("帖子更新成功 Article id = " + id + "user id =" + user.getId());
                        return AppResult.success(true);
                    }
                    return AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE);
                }
                return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
            }
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
    }

    /**
     * date: 2024/09/15 17:32<br/>
     * Description: 跟新点赞数
     *
     * @author: jmy <br/>
     */
    @ApiOperation("更新点赞数")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUpById(HttpServletRequest request, @ApiParam("帖子id") @NotNull @RequestParam("id") Long id) {
        log.info("article/thumbsUp 接收参数: id:" + id);
        if (id <= 0) {
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //获取登录用户的信息
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);
        //判断登录用户是否被禁言
        if (user.getState() == 1) {
            log.error(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        if (articleServices.thumbsUpById(id)) {
            return AppResult.success();
        }
        return AppResult.failed(ResultCode.FAILED);
    }

    /**
     * date: 2024/09/16 10:13<br/>
     * Description: 删除文章
     *
     * @param id 被删除的帖子id
     * @author: jmy <br/>
     */
    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @ApiParam("帖子id") @NotNull @RequestParam("id") Long id) {
        //参数校验
        log.info("article/delete 接收参数: id = " + id);
        if (id <= 0) {
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        //判断用户是否处于禁言状态
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            log.error(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED.getMessagesg());
        }

        //判断帖子状态
        Article article = articleServices.selectById(id);
        if (article == null) {
            log.error(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        //判断板块是否异常
        Board board = boardServices.selectByPrimaryKey(article.getBoardId());
        if (board == null) {
            log.error(ResultCode.FAILED_BOARD_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }

        //判断登录用户是否等于 帖子作者
        if (!Article.judge(user.getId(), article.getUserId())) {
            log.error(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }

        //删除操作
        Integer result = articleServices.delete(id);
        if (result == 0) {
            return AppResult.failed(ResultCode.FAILED_CREATE.toString());
        }

        return AppResult.success("删除帖子成功");
    }

    @ApiOperation("查询用户帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult getAllByUserId(HttpServletRequest request,
                                    @ApiParam("用户id") @NotNull @RequestParam(value = "userId", required = false) Long userId) {
        //获取登录用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //
        if (userId == null) {
            userId = user.getId();
        }

        //获取帖子列表并返回
        List<Article> articles = articleServices.selectByUserId(userId);
        return AppResult.success(articles);
    }
}
